<template>
  <div>
    <div class="user-container">
      <!-- 功能栏 -->
      <el-form :inline="true" :model="searchMap">
        <el-form-item>
          <el-input
            v-model="searchMap.name"
            @keydown.enter.native="searchEnter"
            onkeypress="if(event.keyCode == 13) return false;"
            placeholder="请输入用户名或姓名"
            @input="searchInput"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearchSubmit" class="search-mr"
            >查询</el-button
          >
          <el-button @click="handleAdd" type="primary" plain>新增</el-button>
          <!--	v-if="permission.add" v-if="permission.modify" -->
          <!-- <el-button @click="handleEdit" type="primary" plain>编辑</el-button> -->
          <!-- <el-button
            v-if="permission.delete"
            @click="handleDelete"
            type="primary"
            plain
            >删除</el-button
          > -->
          <el-button @click="handleElectricityquota" type="primary" plain>
            修改用电免费额度</el-button
          >
          <el-button @click="handleElectricityquotarecord" type="primary" plain
            >用户免费额度记录</el-button
          >
          <el-button
            v-if="permission.modify"
            @click="handleEnableDisable"
            type="primary"
            plain
            >启用/禁用</el-button
          >

          <el-button
            v-if="permission.group"
            @click="handleGetGroupData"
            type="primary"
            style="margin-left: 40px"
            plain
          >
            所属组</el-button
          >
          <el-button
            v-if="permission.role"
            @click="handleGetRoleData"
            type="primary"
            plain
            >所任角色</el-button
          >
          <el-button
            v-if="permission.area"
            @click="handleManageArea"
            type="primary"
            plain
            >管理区域</el-button
          >
          <el-button
            v-if="$store.getters.user.manager >0"
            @click="handleAuditDisable"
            type="primary"
            plain
            >待审核用户</el-button
          >
        </el-form-item>
      </el-form>

      <!-- table数据 -->
      <el-table
        ref="multipleTable"
        :data="tableData"
        @selection-change="handleSelectionChange"
        @sort-change="sortchange"
        border
        tooltip-effect="dark"
        style="width: auto; overflow: hidden"
        :row-key="
          (row) => {
            return row.id;
          }
        "
      >
        <el-table-column type="selection" width="40" :reserve-selection="true">
        </el-table-column>
        <el-table-column type="index" label="序号" width="50">
        </el-table-column>
        <el-table-column prop="userName" label="用户名"> </el-table-column>
        <el-table-column prop="name" label="姓名"> </el-table-column>
        <el-table-column prop="phone" label="电话"> </el-table-column>
        <!-- <el-table-column prop="email" label="电子邮箱"> </el-table-column> -->

        <el-table-column
          sortable="custom"
          prop="manager"
          label="管理员等级"
          width="120"
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.manager == 2
                ? "客户管理员 "
                : scope.row.manager == 1
                ? "普通管理员"
                : "普通用户"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间">
        </el-table-column>
        <el-table-column
          sortable="custom"
          prop="userQuota"
          label="剩余免费额度/总免费额度"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.userQuota != null"
              >{{ scope.row.userQuota | WhtokWh }}/{{
                scope.row.userQuotaAmount | WhtokWh
              }}</span
            >
            <span v-if="scope.row.userQuota == null">暂未配置</span>
          </template>
        </el-table-column>
        <el-table-column label="编辑操作" width="350">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
              >信息</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="handleEditOrgan(scope.row)"
              >网点</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="handleManageArea(scope.row)"
              >区域</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="handleGetRoleData(scope.row)"
              >角色</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="text-align: right"
      >
      </el-pagination>

      <!-- 新增员工 -->
      <el-dialog
        class="add-user-dia"
        :title="isAddNew ? '新增用户' : '编辑用户信息'"
        :visible.sync="dialogUserVisible"
        width="500px"
        @close="resetPojoForm"
        :close-on-click-modal="false"
      >
        <el-steps
          v-if="isAddNew"
          :active="active"
          align-center
          class="addusersteps"
          finish-status="success"
        >
          <el-step title="添加用户信息"> </el-step>
          <el-step title="选择用户管理网点"></el-step>
          <el-step title="选择用户管理区域"></el-step>
        </el-steps>
        <el-form
          style="margin-top: 10px"
          v-show="active == 0"
          :rules="rules"
          :model="pojoUser"
          ref="pojoForm"
          status-icon
          label-position="right"
          label-width="130px"
        >
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="pojoUser.userName"></el-input>
          </el-form-item>
          <el-form-item v-if="isAddNew" label="密码" prop="password">
            <el-input v-model="pojoUser.password" type="password"></el-input>
          </el-form-item>
          <el-form-item v-if="isAddNew" label="确认密码" prop="checkpassword">
            <el-input
              v-model="pojoUser.checkpassword"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="pojoUser.name"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model.number="pojoUser.phone"></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="pojoUser.email"></el-input>
          </el-form-item>
          <el-form-item
            :label="pojoUser.manager == 2 ? `推送邮件：` : '接送邮件：'"
            prop="acceptMail"
          >
            <el-switch
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              v-model="pojoUser.acceptMail"
            ></el-switch>
            <el-tooltip
              class="item"
              effect="dark"
              content="每日8：00推送每日用电量数据报表至邮箱
"
              placement="right"
            >
              <i
                class="el-icon-warning-outline"
                style="color: #fff; font-size: 20px; margin-left: 10px"
              ></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item
            label="是否为管理员"
            v-if="
              this.$store.getters.user.manager == 2 && pojoUser.manager != 2
            "
          >
            <div class="manager-row">
              <el-switch
                v-if="pojoUser.manager != 2"
                style="display: block"
                active-value="1"
                inactive-value="0"
                v-model="pojoUser.manager"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
              <el-tooltip
                class="item"
                effect="dark"
                content="管理员可管理门锁人员以及门锁密码"
                placement="right"
              >
                <i class="el-icon-warning-outline"></i>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-form>

        <div v-show="active == 1">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            class="checkall"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-tree
            class="Organtree"
            :data="OrganByCustomdata"
            show-checkbox
            default-expand-all
            check-on-click-node
            node-key="id"
            ref="Organtree"
            highlight-current
            :props="OrganBdefaultProps"
            @check="handleCheckedCitiesChange"
          >
          </el-tree>
        </div>
        <div v-show="active == 2">
          <div v-show="orgidisnull">
            <div
              style="
                text-align: center;
                font-size: 0.18rem;
                color: #fff;
                margin-top: 10px;
              "
            >
              未对用户进行公司分配，可以直接提交
            </div>
          </div>
          <div v-show="!orgidisnull">
            <div style="margin-top: 20px">
              <h4
                style="
                  font-size: 0.16rem;
                  font-weight: 300;
                  margin-right: 10px;
                  display: inline-block;
                "
              >
                选择网点
              </h4>
              <el-select
                v-model="orgid"
                @change="selectaddOrganChange"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in organcheckdata"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
            <div style="height: 300px">
              <el-scrollbar wrap-class="scrollbar-wrapper" style="height: 100%">
                <el-tree
                  :data="AreaTreeByOrgandata"
                  ref="refAreaTreeByOrgandataTree"
                  show-checkbox
                  node-key="id"
                  :check-strictly="true"
                  :props="AreaTreeByOrganProps"
                  @check="dialogAreaTreeByOrganChange"
                >
                  <!-- -->
                </el-tree>
              </el-scrollbar>
            </div>
            <div>
              <div style="font-size: 0.16rem; color: #fff">已选区域</div>
              <el-checkbox-group v-model="areaIdList">
                <el-checkbox
                  v-for="item in areacheckdata"
                  :label="item.id"
                  :key="item.id"
                  @change="editAddreacheckdata(item.id)"
                  >{{ item.name }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
          </div>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button
            v-if="isAddNew"
            type="primary"
            @click="addEmployeeSubmit('pojoForm')"
            >创建用户</el-button
          >
          <el-button
            v-if="active != 0 && isAddNew"
            type="primary"
            @click="Previous"
            >上一步</el-button
          >
          <el-button v-if="active != 2 && isAddNew" type="primary" @click="next"
            >下一步</el-button
          >
          <el-button
            v-if="active == 2 && isAddNew"
            type="primary"
            @click="addEmployeeSubmit('pojoForm')"
            >确 定
          </el-button>

          <el-button
            v-if="!isAddNew"
            type="primary"
            @click="editEmployeeSubmit('pojoForm')"
            >确 定</el-button
          >
          <el-button @click="dialogUserVisible = false">取 消</el-button>
        </div>
      </el-dialog>
      <!--编辑用户充电配额-->
      <!-- 新增员工 -->
      <el-dialog
        class="add-user-dia"
        title="编辑用户充电配额"
        :visible.sync="Electricityquotashow"
        width="500px"
        :close-on-click-modal="false"
      >
        <el-form
          :rules="Electricityquotarules"
          status-icon
          ref="ElectricityquotaForm"
          :model="Electricityquotaform"
          label-position="right"
          label-width="100px"
        >
          <el-form-item label="用户配额" prop="Electricityquota">
            <el-input
              v-model.number="Electricityquotaform.quota"
              style="width: 300px"
            ></el-input>
            <span style="color: #fff; margin-left: 10px">度/月</span>
          </el-form-item>
        
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            @click="editElectricityquotaSubmit('ElectricityquotaForm')"
            >确 定</el-button
          >
          <el-button @click="Electricityquotashow = false">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 所属组 -->
      <el-dialog
        class="group-dia"
        title="所属组"
        :visible.sync="dialogGroupVisible"
        @close="dialogGroupClose"
        :close-on-click-modal="false"
      >
        <div class="diolog-group-table">
          <div style="width: 45%">
            <h4>已加入组</h4>
            <el-table
              :data="ManageData_group"
              border
              style="margin-top: 10px"
              @selection-change="handleManageGroupSel"
            >
              <el-table-column type="selection" width="40"> </el-table-column>
              <el-table-column type="index" label="序号" width="50">
              </el-table-column>
              <el-table-column prop="name" label="组名"> </el-table-column>
              <el-table-column prop="remark" label="标签"> </el-table-column>
            </el-table>
          </div>
          <div class="dialog-group-btn">
            <el-button
              @click="dialogHandleGroupChange('add')"
              :disabled="multipleAvailableGroupSel.length == 0"
              size="small"
              type="primary"
              icon="el-icon-d-arrow-left"
              >新 增</el-button
            >
            <el-button
              @click="dialogHandleGroupChange('delete')"
              :disabled="multipleManageGroupSel.length == 0"
              size="small"
              type="primary"
              >移 除<i class="el-icon-d-arrow-right"></i
            ></el-button>
          </div>
          <div style="width: 45%">
            <h4>可选组</h4>
            <el-table
              :data="AvailableData_group"
              border
              style="margin-top: 10px"
              @selection-change="handleAvailableGroupSel"
            >
              <el-table-column type="selection" width="40"> </el-table-column>
              <el-table-column type="index" label="序号" width="50">
              </el-table-column>
              <el-table-column prop="name" label="组名"> </el-table-column>
              <el-table-column prop="remark" label="标签"> </el-table-column>
            </el-table>
          </div>
        </div>
      </el-dialog>

      <!-- 所任角色 -->
      <el-dialog
        class="group-dia"
        title="所任角色"
        :visible.sync="dialogRoleVisible"
        @close="dialogGroupClose"
        width="600px"
        :close-on-click-modal="false"
      >
        <el-transfer
          class="shuttle-row"
          :titles="['未添加角色', '已添加角色']"
          :button-texts="['移除', '添加']"
          :props="UserBindRoledataProps"
          v-model="UserBindRole"
          @change="handleEditUserRolechange"
          :data="UserRoledata"
        >
        </el-transfer>
        <div style="text-align: center; margin-top: 20px">
          <el-button size="medium" @click="dialogRoleVisible = false"
            >取 消</el-button
          >
        </div>
      </el-dialog>

      <!-- 管理的区域 -->
      <el-dialog
        title="管理区域"
        :visible.sync="dialogManageAreaVisible"
        width="1200px"
        @close="clearManageAreaData"
        :close-on-click-modal="false"
      >
        <div class="dialog-area-head">
          <h4>管理的区域</h4>
          <div>
            <el-select
              style="margin-right: 10px"
              clearable
              size="small"
              v-model="Organinarea"
              @change="selectOrganainareaChange"
              placeholder="请选择"
            >
              <el-option
                v-for="item in organOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-button @click="dialogAddArea" size="small" type="primary"
              >添 加</el-button
            >
            <el-button @click="dialogAddDelete" size="small" type="primary"
              >移 除</el-button
            >
          </div>
        </div>
        <el-table
          :data="dialogManageAreaData"
          @selection-change="handleManageAreaChange"
          border
          style="width: 100%; margin-top: 10px"
          height="400px"
        >
          <el-table-column type="selection" width="40"> </el-table-column>
          <el-table-column type="index" label="序号" width="50">
          </el-table-column>
          <el-table-column prop="organId" label="网点" width="150">
            <template slot-scope="scope">
              <div>{{ scope.row.organId | getorganName() }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="areaName" label="区域" width="150">
          </el-table-column>
          <!-- <el-table-column prop="delegated" label="是否为托管" width="100">
            <template slot-scope="scope">
              <el-checkbox
                :true-label="1"
                :false-label="0"
                v-model="scope.row.delegated"
                @change="trusteeship(scope.row)"
                >托管</el-checkbox
              >
            </template>
          </el-table-column> -->
          <el-table-column prop="targetCategoryIds" label="电器类型">
            <template slot-scope="scope">
              <el-checkbox-group
                :min="1"
                v-model="scope.row.targetCategoryId"
                @change="
                  (val) => {
                    checkboxTargetCateGory(val, scope.row);
                  }
                "
              >
                <el-checkbox
                  v-for="item in channelTargetCategory"
                  :key="item.id"
                  :label="item.id"
                >
                  {{ item.name }}
                </el-checkbox>
              </el-checkbox-group>
            </template>
          </el-table-column>
        </el-table>
        <div class="close-box">
          <el-button
            size="medium"
            type="primary"
            @click="dialogManageAreaVisible = false"
            >关 闭</el-button
          >
        </div>
      </el-dialog>
      <el-dialog
        title="添加区域"
        :visible.sync="dialogAddAreaVisible"
        width="500px"
        @close="reGetUserBindAreaData"
        :close-on-click-modal="false"
      >
        <div>
          <h4 style="margin-right: 20px; display: inline-block">选择网点</h4>
          <el-select
            v-model="dialogOrganValue"
            @change="selectOrganChange"
            placeholder="请选择"
          >
            <el-option
              v-for="item in organOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
        <div style="height: 300px">
          <el-scrollbar wrap-class="scrollbar-wrapper" style="height: 100%">
            <el-tree
              :data="dialogAreaData"
              ref="refdialogAreaTree"
              show-checkbox
              node-key="id"
              :props="defaultProps"
              @check="dialogTreeChange"
            >
            </el-tree>
          </el-scrollbar>
        </div>

        <div style="text-align: center; margin-top: 20px">
          <el-button @click="submitAddManageArea" size="medium" type="primary"
            >确 定</el-button
          >
          <el-button size="medium" @click="dialogAddAreaVisible = false"
            >取 消</el-button
          >
        </div>
      </el-dialog>

      <el-dialog
        title="编辑用户管理网点"
        :visible.sync="dialogEditOrganVisible"
        width="600px"
        :close-on-click-modal="false"
      >
        <el-transfer
          class="shuttle-row"
          :titles="['未添加网点', '已添加网点']"
          :button-texts="['移除', '添加']"
          :props="OrganByCustomdataProps"
          v-model="UserBindOrgan"
          @change="handleEditOrganchange"
          :data="OrganByCustomdata"
        >
         <span slot-scope="{ option }" :title="option.name"> {{ option.name }}</span>
        </el-transfer>

        <div style="text-align: center; margin-top: 20px">
          <el-button size="medium" @click="dialogEditOrganVisible = false"
            >取 消</el-button
          >
        </div>
      </el-dialog>

      <el-dialog
        :title="Electricityquotarecordtitle + '用电配额操作记录'"
        :visible.sync="ElectricityquotarecordVisible"
        width="850px"
        :close-on-click-modal="false"
      >
        <div>
          <div style="text-align: right; color: #fff; margin-bottom: 10px">
            额度单位：度
          </div>
          <el-table
            :data="Electricityquotarecorddata"
            border
            tooltip-effect="dark"
            style="width: auto"
            :max-height="tableHeight"
          >
            <el-table-column
              type="index"
              label="序号"
              width="50"
              align="center"
            >
            </el-table-column>
            <el-table-column prop="optime" label="事件">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.endCase }}

                  <!-- {{
                      scope.row.optime == "分配配额"
                        ? "分配配额-操作人:" + scope.row.endTime
                        : "开始时间：" + scope.row.createTime
                  }} -->
                </div>

                <!-- <div>	{{scope.row.optime=="分配配额"?"":'结束时间:'+scope.row.edtime}}</div> -->
              </template>
            </el-table-column>
            <el-table-column prop="optime" label="时间">
              <template slot-scope="scope">
                <div>
                  {{ "开始时间：" + scope.row.startTime }}

                  <!-- {{
                      scope.row.optime == "分配配额"
                        ? "分配配额-操作人:" + scope.row.endTime
                        : "开始时间：" + scope.row.createTime
                  }} -->
                </div>
                <div>
                  {{ "结束时间：" + scope.row.endTime }}
                </div>
                <!-- <div>	{{scope.row.optime=="分配配额"?"":'结束时间:'+scope.row.edtime}}</div> -->
              </template>
            </el-table-column>
            <!-- <el-table-column prop="chargingTime" label="充电时长" align="center" width="100">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.chargingTime | mintoH }}
                </div>
              </template>
            </el-table-column> -->
            <!-- <el-table-column prop="quotaBefore" align="center" label="可使用额度" width="100">
							<template slot-scope="scope">
								<div >
								
									{{scope.row.quotaBefore| WhtokWh}}
								</div>
							</template>
					</el-table-column> -->
            <el-table-column
              prop="quota"
              label="当次使用额度"
              align="center"
              width="130"
            >
              <template slot-scope="scope">
                <div>-{{ scope.row.quota | WhtokWh }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="quotaAfter"
              align="center"
              label="本周期剩余额度"
              width="130"
            >
              <template slot-scope="scope">
                <div>
                  {{ scope.row.quotaAfter | WhtokWh }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>

      <el-dialog
        title="待审核用户"
        :visible.sync="dialogAuditVisible"
        width="600px"
        :close-on-click-modal="false"
      >
        <el-table
          :data="Auditdata"
          height="350px"
          border
          tooltip-effect="dark"
          style="width: auto; overflow: hidden"
        >
          <el-table-column type="index" label="序号" width="50">
          </el-table-column>

          <el-table-column prop="name" label="姓名" width="400">
          </el-table-column>

          <el-table-column label="审核操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleAuditVisible(scope.row)"
                >审核</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
      <el-dialog  title="审核用户分配区域"
        :visible.sync="dialogAuditactiveUserVisible"
        width="350px"
        @close="resetAudita"
        :close-on-click-modal="false">
        
        <div v-show="Auditactive == 0">
          <div style="margin-top: 20px">
              <h4 style="font-size: 0.16rem;font-weight: 300;margin-right: 10px;display: inline-block;">
                选择网点：
              </h4>
              <el-select
                v-model="orgid"
                @change="selectaddOrganChange"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in OrganByCustomdata"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
            <div style="margin-top: 20px">
              <h4 style="font-size: 0.16rem;font-weight: 300;margin-right: 10px;display: inline-block;">
                选择分组：
              </h4>
              <el-select
                v-model="quartzGroupId"
                @change="selectquartzGroupChange"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in QuartzGroup"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
        
        </div>
     
        <div slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            @click="handleAudit()"
            >确 定
          </el-button>
          <el-button @click="dialogAuditactiveUserVisible = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import ajax from "@/utils/ajax";
import Transfer from "@/components/Transfer";
import { tableSelection, deleteConfirm } from "@/utils/elementui";
import axios from "axios";
const roleOptions = [
  { type: "M", name: "管理员" },
  { type: "E", name: "技术员" },
  { type: "R", name: "座席" },
  { type: "G", name: "安保" },
];
const statusOptions = [
  { type: "N", name: "禁用" },
  { type: "Y", name: "启用" },
];
let organOptions = [];
export default {
  components: { Transfer },
  data() {
    let validPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("密码不能为空"));
      } else {
        if (this.pojoUser.checkpassword !== "") {
          this.$refs.pojoForm.validateField("checkpassword");
        }
        callback();
      }
    };
    let validCheckPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("确认密码不能为空"));
      } else if (value !== this.pojoUser.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    let checkUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      } else {
        if (this.editUsernamechecking == value && this.isAddNew == false) {
          return callback();
        } else {
          let cod = this.tableData.findIndex((item) => item.userName == value);
          if (cod != -1) {
            return callback(new Error("输入的用户名已存在"));
          } else {
            return callback();
          }
        }
      }
    };
    let checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("电话不能为空"));
      }
      if (!Number.isInteger(value)) {
        //console.log(value)
        return callback(new Error("请输入正确的电话"));
      } else {
        if (this.editphonechecking == value && this.isAddNew == false) {
          return callback();
        } else {
          let cod = this.tableData.findIndex((item) => item.phone == value);
          if (cod != -1) {
            return callback(new Error("输入的电话已存在"));
          } else {
            return callback();
          }
        }
      }
    };
    return {
      tableHeight: 300,
      editphonechecking: "",
      editUsernamechecking: "",
      tableDatachecking: [],
      permission: {
        get: true,
        modify: false,
        add: false,
        delete: false,
        group: false,
        role: false,
        area: false,

        has_role: false,
        available_role: false,
        role_add: false,
        role_delete: false,
      },
      customerId: null,
      organId: null,

      tableData: [],
      AlltableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchMap: {
        name: "",
      },
      dialogUserVisible: false,
      roleOptions,
      pojoUser: {
        customerId: this.$store.getters.customerId,
        userName: "",
        password: "",
        manager: 0,
        checkpassword: "",
        name: "",
        phone: "",
        email: "",
        acceptMail: 0,
      },
      rules: {
        userName: [
          { required: true, validator: checkUsername, trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { validator: validPassword, trigger: "blur" },
        ],
        checkpassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { validator: validCheckPassword, trigger: "blur" },
        ],
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        phone: [{ required: true, validator: checkPhone, trigger: "blur" }],
        email: [
          // { required: true, message: '电子邮箱不能为空', trigger: 'blur' },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
      },
      multipleSelection: [],
      isAddNew: true,
      isUserEnable: false,

      dialogManageAreaVisible: false,
      dialogManageAreaData: [],
      alldialogManageAreaData: [],
      multipleAreaSelection: [],
      dialogAddAreaVisible: false,
      dialogOrganValue: "",
      organOptions: [],
      dialogAreaData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      dialogAreaNodeCheck: [],
      checkedKeysArea: [],

      channelTargetCategory: [],

      // 所属组
      dialogGroupVisible: false,
      ManageData_group: [],
      AvailableData_group: [],
      multipleAvailableGroupSel: [],
      multipleManageGroupSel: [],

      currentTransfer: null,
      //充电配额
      Electricityquotashow: false,
      Electricityquotaform: {
        quota: "",
        // Electricityquotatype: '',
        userId: -1,
      },
      Electricityquotarules: {
        quota: [
          { required: true, message: "不能为空", trigger: "blur" },
          { type: "number", message: "必须为数字值", trigger: "blur" },
        ],
        // Electricityquotatype: [
        //   { required: true, message: '请至少选择一个', trigger: 'change' }
        // ]
      },
      //使用记录
      ElectricityquotarecordVisible: false,
      Electricityquotarecorddata: [],
      Electricityquotarecordtitle: "",

      //分步表单
      active: 0,
      OrganByCustomdata: [],
      OrganByCustomlenght: null,
      organIdList: [],
      organcheckdata: [],
      areaIdList: [],
      areacheckdata: [],
      OrganBdefaultProps: {
        label: "name",
      },
      AreaTreeByOrganProps: {
        children: "children",
        label: "name",
      },
      checkAll: false,
      isIndeterminate: false,
      AreaTreeByOrgandata: [],
      AreaTreeByOrgandatalength: null,
      orgid: null,
      orgidisnull: true,

      //编辑用户管理网点
      dialogEditOrganVisible: false,
      UserBindOrgan: [],
      OrganByCustomdataProps: {
        key: "id",
        label: "name",
      },
      editorganuserid: null,
      //角色
      // 角色
      dialogRoleVisible: false,
      transferTitle: "",
      UserRoledata: [],
      UserBindRole: [],
      UserBindRoledataProps: {
        key: "id",
        label: "roleName",
      },
      //网点区域关系
      Organinarea: null,
      dialogAuditVisible: false,
      Auditdata: [],

      //审批
      dialogAuditactiveUserVisible:false,
      Auditactive:0,
      Audituser:{},
      //分组列表
      QuartzGroup:[],
      quartzGroupId:null,
      layoutsid:null
    };
  },
  created() {
    this.customerId = this.$store.getters.customerId;
    // this.setPermission();
    this.getUserListData();
    this.getOrganByCustomdata();
    this.getUserRoledata();
    // this.getUserListDataChecking();
  },
  mounted() {
    this.$store.dispatch("actions/dynamicTitleAction", this.$route.meta.title);
    this.getTargetCategoryData();
  },
  computed: {
    batteryTime() {
      return function (index) {
        if (index.optime == "分配配额") {
          return "--";
        } else {
          return twoTimeInterval(index.optime, index.edtime) + "小时";
        }
      };
    },
  },
  methods: {
    // 设置可操作的权限
    setPermission() {
      // let route_permissions = this.$route.meta.sub_permissions
      let role_permissions = this.$store.getters.rolePermissions;
      console.log(role_permissions);
      for (let item of role_permissions) {
        if (item.action === "/web/user") {
          for (let permission of item.privilegeList) {
            switch (permission.action) {
              case "/web/user/query":
                this.permission.get = true;
                break;
              case "/web/user/modify":
                this.permission.modify = true;
                break;
              case "/web/user/add":
                this.permission.add = true;
                break;
              case "/web/user/delete":
                this.permission.delete = true;
                break;
              case "/web/user/group":
                this.permission.group = true;
                break;
              case "/web/user/role":
                this.permission.role = true;
                break;
              case "/web/user/area":
                this.permission.area = true;
                break;

              default:
                break;
            }
          }
        }
      }
    },
    // 获取用户列表
    getUserListData() {
      let pocustomerId = this.customerId;
      let posearchStr = this.searchMap.name.trim();
      ajax.get({
        url: this.$API.getUserListByCustomerId + pocustomerId,

        success: (response) => {
          //console.log(response)

          this.AlltableData = response.data;
          this.total = response.data.length;
          this.$refs.multipleTable.clearSelection();
          this.initTableData();
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    initTableData() {
      let pageSize = this.pageSize;
      let currentPage = this.currentPage;
      let start = (currentPage - 1) * pageSize;
      let end = start + pageSize;
      // //console.log(this.tableDataAll)
      this.tableData = this.AlltableData.slice(start, end);
      this.$refs.multipleTable.clearSelection();
      // //console.log(this.tableData)
    },
    //
    handleSizeChange(value) {
      this.pageSize = value;
      this.initTableData();
    },
    handlePageChange(value) {
      this.currentPage = value;
      this.initTableData();
    },
    //
    sortchange(column) {
      let prop = column.prop;
      let order = column.order;
      let self = this;

      if (order == "ascending") {
        switch (prop) {
          case "manager":
            this.$nextTick(() => {
              self.AlltableData = self.AlltableData.sort((n1, n2) => {
                return n1.manager - n2.manager;
              });
            });

            break;
          case "lastQuota":
            this.$nextTick(() => {
              self.AlltableData = self.AlltableData.sort((n1, n2) => {
                return n1.lastQuota - n2.lastQuota;
              });
            });
            break;
          default:
            break;
        }
      } else if (order == "descending") {
        switch (prop) {
          case "manager":
            this.$nextTick(() => {
              self.AlltableData = self.AlltableData.sort((n1, n2) => {
                return n2.manager - n1.manager;
              });
            });

            break;
          case "lastQuota":
            this.$nextTick(() => {
              self.AlltableData = self.AlltableData.sort((n1, n2) => {
                return n2.lastQuota - n1.lastQuota;
              });
            });
            break;
          default:
            break;
        }
      }
      self.initTableData();
    },

    // 点击查询
    onSearchSubmit() {
      if (this.searchMap.name.trim() === "") {
        return;
      }
      this.currentPage = 1;
      this.SearchUserListData();
      this.$nextTick(() => {
        this.$refs.multipleTable.clearSelection();
      });
    },
    searchInput(value) {
      if (value.trim() === "" && value.length === 0) {
        this.SearchUserListData();
        this.$nextTick(() => {
          this.$refs.multipleTable.clearSelection();
        });
      }
    },
    searchEnter(e) {
      let keyCode = e.keyCode;
      if (keyCode == 13) {
        this.onSearchSubmit();
      }
    },
    //搜索
    SearchUserListData() {
      if (this.searchMap.name.trim() === "") {
        this.initTableData();
      } else {
        let pageSize = this.pageSize;
        let currentPage = this.currentPage;
        let start = (currentPage - 1) * pageSize;
        let end = start + pageSize;
        // //console.log(this.tableDataAll)
        let Searchdata = this.AlltableData.filter(
          (data) =>
            data.userName
              .toLowerCase()
              .includes(this.searchMap.name.toLowerCase()) ||
            data.phone == this.searchMap.name || data.name.toLowerCase()
              .includes(this.searchMap.name.toLowerCase())
        );

        this.tableData = Searchdata.slice(start, end);
      }
    },
    // 新增
    handleAdd() {
      this.isAddNew = true;
      this.dialogUserVisible = true;
      this.pojoUser.manager = 0;
    },
    // 新增提交
    addEmployeeSubmit(formName) {
      this.pojoUser.organIdList = this.organIdList;
      this.pojoUser.areaIdList = this.areaIdList;

      this.$refs[formName].validate((valid) => {
        if (valid) {
          ajax.post({
            url: this.$API.addUser,
            data: this.pojoUser,
            success: (response) => {
              //console.log(response)
              if (response.success) {
                this.getUserListData();

                this.dialogUserVisible = false;
                this.resetPojoForm();
                this.$message({
                  message: "新增员工成功",
                  type: "success",
                });
              } else {
                this.$message({
                  message: response.message,
                  type: "warning",
                });
              }
            },
            error: (response) => {
              this.$message({
                message: response.message,
                type: "error",
              });
            },
          });
        } else {
          //console.log('验证失败')
        }
      });
    },

    // 编辑
    handleEdit(data) {
      this.isAddNew = false;
      if (!this.isUserEnable) {
        this.dialogUserVisible = true;
      }
      this.$nextTick(() => {
        this.pojoUser.id = data.id;
        this.pojoUser.userName = data.userName;

        this.pojoUser.name = data.name;
        this.pojoUser.manager = data.manager;

        this.pojoUser.phone = parseInt(data.phone) ? parseInt(data.phone) : "";
        this.editphonechecking = parseInt(data.phone)
          ? parseInt(data.phone)
          : "";
        this.editUsernamechecking = data.userName;
        this.pojoUser.email = data.email;
        this.pojoUser.password = data.password;
        this.pojoUser.acceptMail = data.acceptMail;
      });
    },
    // 编辑提交
    editEmployeeSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.pojoUser.state = 1;
          ajax.post({
            url: this.$API.editUser,
            data: this.pojoUser,
            success: (response) => {
              //console.log(response)
              if (response.success) {
                this.getUserListData();

                this.dialogUserVisible = false;
                this.$message({
                  message: "编辑成功",
                  type: "success",
                });
              } else {
                this.$message({
                  message: response.message,
                  type: "warning",
                });
              }
            },
            error: (res) => {
              //console.log(res)
              this.$message({
                message: res.message,
                type: "error",
              });
            },
          });
        } else {
          //console.log('验证失败')
        }
      });
    },

    // 表单重置
    resetPojoForm() {
      this.$refs["pojoForm"].resetFields();

      this.active = 0;
      this.organIdList = [];
      this.organcheckdata = [];
      this.areaIdList = [];
      this.areacheckdata = [];
      this.AreaTreeByOrgandata = [];
      this.$refs.Organtree.setCheckedNodes([]);
      this.isIndeterminate = false;
      this.checkAll = false;
    },
    //用户充电量配额
    handleElectricityquota() {
      let selectionArr = this.multipleSelection;
      let selResult = tableSelection(selectionArr, 0);
      if (selResult) {
        this.Electricityquotaform.userId = selectionArr[0].id;
        this.Electricityquotaform.quota =
          selectionArr[0].quota == null ? "" : selectionArr[0].quota / 1000;
        this.Electricityquotashow = true;
      }
    },
    editElectricityquotaSubmit(formName) {
      let data = [];
      for (let item of this.multipleSelection) {
        let attr = {};
        attr.userId = item.id;
        attr.quota = this.Electricityquotaform.quota * 1000;
        data.push(attr);
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          ajax.post({
            url: this.$API.addUserQuota,
            data: data,
            success: (response) => {
              //console.log(response)
              if (response.success) {
                this.Electricityquotashow = false;
                // 成功后，重新获取数据
                this.$message({
                  type: "success",
                  message: response.message,
                });
                this.getUserListData();
                // this.getUserListDataChecking();
              }
            },
            error: (res) => {
              //console.log(res)
              this.$message({
                message: res.message,
                type: "error",
              });
            },
          });
          console.log(this.Electricityquotaform);
        } else {
          return false;
        }
      });
    },
    //删除
    handleDelete(data) {
      if (data.manager == 2) {
        this.$message({
          message: "删除用户包含客户管理员,不可删除",
          type: "error",
        });
      } else {
        deleteConfirm(this).then((res) => {
          if (res) {
            ajax.post({
              url: this.$API.deleteUser + data.id,
              success: (response) => {
                //console.log(response)
                if (response.success) {
                  // 成功后，重新获取数据
                  this.getUserListData();

                  this.$refs.multipleTable.clearSelection();
                  this.$message({
                    type: "success",
                    message: response.message,
                  });
                }
              },
              error: (res) => {
                //console.log(res)
                this.$message({
                  message: res.message,
                  type: "error",
                });
              },
            });
          }
        });
      }
    },

    // 启用/禁用
    handleEnableDisable() {
      // this.isUserEnable = true
      // this.handleEdit()
      let selectionArr = this.multipleSelection;
      let selResult = tableSelection(selectionArr, 0);
      if (selectionArr.findIndex((data) => data.manager == 2) != -1) {
        this.$message({
          message: "禁用用户包含客户管理员,不可禁用",
          type: "error",
        });
      } else {
        if (selResult) {
          // let status = selectionArr[0].status
          // let message = ''
          // if (status == 'N') {
          // 	status = 'Y'
          // 	message = '启用成功'
          // } else {
          // 	status = 'N'
          // 	message = '禁用成功'
          // }
          // this.pojoUser.status = status
          //console.log(this.pojoUser)
          let idsArr = [];
          for (let item of selectionArr) {
            idsArr.push(item.id);
          }
          let po_ids = idsArr.join(",");
          ajax.post({
            url: this.$API.modifyUserStatus,
            data: {
              ids: po_ids,
            },
            success: (response) => {
              //console.log(response)
              this.$message({
                message: response.message,
                type: "success",
              });
              this.getUserListData();
            },
            error: (res) => {
              //console.log(res)
              this.$message({
                message: res.message,
                type: "error",
              });
            },
          });
        }
      }
      this.isUserEnable = false;
    },

    // 获取所属组的数据
    handleGetGroupData() {
      let selectionArr = this.multipleSelection;
      let selResult = tableSelection(selectionArr, 1);
      if (selResult) {
        // 获取数据
        let po_customerId = this.customerId;
        let po_userId = this.multipleSelection[0].id;
        ajax.post({
          url: this.$API.getUserGroup,
          data: { userId: po_userId, customerId: po_customerId },
          success: (response) => {
            //console.log(response)
            const resp = response.data;
            this.AvailableData_group = resp.availableGroup;
            this.ManageData_group = resp.manageGroup;
          },
          error: (res) => {
            //console.log(res)
            this.$message({
              message: res.message,
              type: "error",
            });
          },
        });
        this.dialogGroupVisible = true;
      }
    },

    // 选择管理的用户组
    handleManageGroupSel(value) {
      this.multipleManageGroupSel = value;
    },
    // 勾选可选的用户组
    handleAvailableGroupSel(value) {
      this.multipleAvailableGroupSel = value;
    },
    // 加入和退出组
    dialogHandleGroupChange(type) {
      let po_userId = this.multipleSelection[0].id;
      let changeArr = [];
      let po_url = "";
      let po_data = {};
      if (type === "add") {
        // 加入组
        let addGroupArr = this.multipleAvailableGroupSel;
        // manageGroup = addGroupArr.concat(manageGroup)
        for (let item of addGroupArr) {
          changeArr.push(item.id);
        }
        po_url = this.$API.modifyUserGroup;
        let po_groupId = changeArr.join(",");
        po_data = {
          userId: po_userId,
          groupId: po_groupId,
        };
      } else {
        // 退出组
        let deleteGroupArr = this.multipleManageGroupSel;
        for (let item of deleteGroupArr) {
          changeArr.push(item.id);
        }
        po_url = this.$API.deleteUserGroup;
        let po_groupId = changeArr.join(",");
        po_data = {
          id: po_userId,
          ids: po_groupId,
        };
      }

      ajax.post({
        url: po_url,
        data: po_data,
        success: (response) => {
          if (response.success) {
            //console.log(response)
            this.handleGetGroupData();
            this.$message({
              message: "操作成功",
              type: "success",
            });
          }
        },
        error: (res) => {
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },

    // 关闭弹框
    dialogGroupClose() {
      this.UserBindRole = [];
    },
    // 获取所有角色
    //根据客户获取
    getUserRoledata() {
      ajax.get({
        url: this.$API.getroleList,
        success: (response) => {
          this.UserRoledata = response.data;
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    // 获取用户拥有角色
    handleGetRoleData(data) {
      this.transferTitle = "角色";
      this.dialogRoleVisible = true;
      this.editorganuserid = data.id;
      ajax.get({
        url: this.$API.getUserRole + data.id,
        success: (response) => {
          this.UserBindRole = [];
          if (response.data.length > 0) {
            response.data.forEach((data) => {
              this.UserBindRole.push(data.id);
            });
          }
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },

    handleEditUserRolechange(value, direction, movedKeys) {
      // console.log(value, direction, movedKeys)
      let self = this;
      //添加
      if (direction == "right") {
        axios
          .post(this.$API.addUserRole + this.editorganuserid, movedKeys)
          .then(function (res) {
            if (res.data.success) {
              self.$message({
                message: "角色添加成功",
                type: "success",
              });
            }
          });
      }
      //移除
      else {
        axios
          .post(this.$API.deleteUserRole + this.editorganuserid, movedKeys)
          .then(function (res) {
            if (res.data.success) {
              self.$message({
                message: "角色移除成功",
                type: "success",
              });
            }
          });
      }
    },

    // 管理区域
    handleManageArea(data) {
      this.editorganuserid = data.id;
      this.getOrganListData();

      this.dialogManageAreaVisible = true;
    },
    // 请求弹框用户已管理的区域数据
    getUserBindAreaData() {
      ajax.get({
        url: this.$API.getUserTarget + this.editorganuserid,
        // data: { userId: poId },
        success: (response) => {
          //console.log(response)
          const resp = response.data;

          if (resp.length > 0) {
            for (let item of resp) {
              let targetCategoryIdsArr = [];
              if (item.targetCategoryList) {
                for (let i of item.targetCategoryList) {
                  targetCategoryIdsArr.push(i.id);
                }
              }
              item.targetCategoryId = targetCategoryIdsArr;
            }
          }

          this.dialogManageAreaData = resp;
          this.alldialogManageAreaData = resp;
          //console.log(this.dialogManageAreaData)
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    // 获取通道类型数据
    getTargetCategoryData() {
      ajax.get({
        url: this.$API.getDictTargetCategoryList,
        data: {},
        success: (response) => {
          //console.log(response)
          this.channelTargetCategory = response.data;
          //
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    // 勾选管理区域
    handleManageAreaChange(value) {
      this.multipleAreaSelection = value;
    },
    //处理复选框选中
    checkValue(targetCategoryIds, targetCategoryDataId) {
      // //console.log(targetCategoryIds, targetCategoryDataId)
      if (targetCategoryIds === "0") {
        return true;
      }
      if (targetCategoryIds.indexOf(targetCategoryDataId) !== -1) {
        return true;
      }
    },
    // 选择电器事件
    checkboxTargetCateGory(value, rowData) {
      let po_targetCategoryIds = value.join(",");
      console.log(value, rowData);
      ajax.post({
        url: this.$API.modifUserTarget + rowData.id,
        data: {
          userId: rowData.userId,
          areaId: rowData.areaId,
          targetCategoryId: po_targetCategoryIds,
        },
        success: (response) => {
          //console.log(response)
          if (response.success) {
            this.$message({
              message: "操作成功",
              type: "success",
            });
          }
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    selectOrganainareaChange() {
      let all = this.alldialogManageAreaData;
      this.dialogManageAreaData = this.Organinarea
        ? all.filter((item) => item.organId == this.Organinarea)
        : all;
    },
    clearManageAreaData() {
      this.dialogManageAreaData = [];
      this.alldialogManageAreaData = [];
      this.Organinarea = null;
    },
    // 添加管理的区域
    dialogAddArea() {
      if (this.organId) {
        this.getAreaListData();
      }
      this.dialogAddAreaVisible = true;
    },
    // 获取网点列表
    getOrganListData() {
      ajax.get({
        url: this.$API.getUserOrgan + this.editorganuserid,

        success: (response) => {
          //console.log(response)

          const resp = response.data;
          if (resp.length > 0) {
            this.organOptions = resp;
            organOptions = resp;
          } else {
            this.organOptions = [];
            organOptions = [];
          }
          this.getUserBindAreaData();
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    // 切换网点
    selectOrganChange(value) {
      this.organId = value;
      this.getAreaListData();
    },
    // 获取区域数据
    getAreaListData() {
      let po_organId = this.organId;

      ajax.get({
        url:
          this.$API.getAreaByOrganIdAndUserUnBind +
          `${po_organId}/${this.editorganuserid}`,
        success: (response) => {
          console.log(response);
          const resp = response.data;
          this.dialogAreaData = resp;
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    // 点击树的复选框
    dialogTreeChange() {
      let checkArr = this.$refs.refdialogAreaTree.getCheckedNodes();
      this.dialogAreaNodeCheck = checkArr;
      //console.log(checkArr)
    },
    // 点击确定添加管理区域
    submitAddManageArea() {
      let self = this;
      let po_areaId = this.$refs.refdialogAreaTree.getCheckedKeys();

      //console.log('userId：', po_userId)
      //console.log('areaId', po_areaId)
      axios
        .post(this.$API.userBindTarget + this.editorganuserid, po_areaId)
        .then(function (res) {
          if (res.data.success) {
            self.dialogAddAreaVisible = false;
            self.$message({
              message: "新增成功",
              type: "success",
            });
          }
        });
    },
    // 重新获取绑定区域的数据
    reGetUserBindAreaData() {
      this.getUserBindAreaData();
    },
    // 移除管理的区域
    dialogAddDelete() {
      let self = this;
      let selections = this.multipleAreaSelection;

      let selResult = tableSelection(selections, 0);
      if (selResult) {
        deleteConfirm(this).then((res) => {
          if (res) {
            if (selections.length == 1) {
              ajax.post({
                url: this.$API.userUnBindTarget + selections[0].id,
                success: (response) => {
                  //console.log(response)
                  this.getUserBindAreaData();
                  if (response.success) {
                    this.$message({
                      message: "删除成功",
                      type: "success",
                    });
                  }
                },
                error: (res) => {
                  //console.log(res)
                  this.$message({
                    message: res.message,
                    type: "error",
                  });
                },
              });
            } else {
              let attr = [];
              selections.forEach((data) => {
                attr.push(data.id);
              });

              axios
                .post(this.$API.userUnBindTargetList, attr)
                .then(function (res) {
                  if (res.data.success) {
                    self.dialogAddAreaVisible = false;
                    self.$message({
                      message: "删除成功",
                      type: "success",
                    });
                    self.getUserBindAreaData();
                  }
                });
            }
          }
        });
      }
    },
    trusteeship(row) {
      ajax.post({
        url: this.$API.setTargetAreaDelegated,
        data: {
          userId: row.userId,
          areaId: row.areaId,
          delegated: row.delegated,
        },
        // data:{id:77},
        success: (response) => {
          this.$message({
            message: "设置成功",
            type: "success",
          });
        },
        error: (res) => {
          //console.log(res)
          row.delegated = 1;
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleElectricityquotarecord() {
      let self = this;
      let selectionArr = this.multipleSelection;
      let selResult = tableSelection(selectionArr, 1);
      if (selResult) {
        ajax.get({
          url: this.$API.getUserQuotaLogById + selectionArr[0].id,

          // data:{id:77},
          success: (response) => {
            this.ElectricityquotarecordVisible = true;

            if (response.code == 0) {
              self.Electricityquotarecorddata = response.data;
              //console.log(self.Electricityquotarecorddata);
              this.$nextTick(() => {
                this.Electricityquotarecordtitle = selectionArr[0].name;
              });
            }
          },
          error: (res) => {
            //console.log(res)
            this.$message({
              message: res.message,
              type: "error",
            });
          },
        });
      }
    },
    next() {
      switch (this.active) {
        case 0:
          this.$refs["pojoForm"].validate((valid) => {
            if (valid) {
              this.active++;
            }
          });
          break;
        case 1:
          this.organIdList = this.$refs.Organtree.getCheckedKeys();
          this.organcheckdata = this.$refs.Organtree.getCheckedNodes();
          this.orgid = this.organIdList[0];
          if (this.orgid == undefined) {
            this.orgidisnull = true;
          } else {
            this.orgidisnull = false;
            this.getAreaTreeByOrgandata();
          }
          this.active++;
          break;
        case 2:
          if (this.active++ > 2) this.active = 3;
          break;
        default:
          break;
      }
    },
    Previous() {
      if (this.active-- == 0) this.active = 0;
    },
    //根据客户获取
    getOrganByCustomdata() {
      ajax.get({
        url: this.$API.getOrganByCustomId + this.customerId,
        success: (response) => {
          this.OrganByCustomdata = response.data;
          this.OrganByCustomlenght = response.data.length;
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    //网点全选
    handleCheckAllChange(val) {
      if (
        this.OrganByCustomlenght == this.$refs.Organtree.getCheckedKeys().length
      ) {
        this.$refs.Organtree.setCheckedNodes([]);
        this.isIndeterminate = false;
        this.checkAll = false;
      } else {
        this.$refs.Organtree.setCheckedNodes(this.OrganByCustomdata);
        this.isIndeterminate = false;
        this.checkAll = true;
      }
    },
    handleCheckedCitiesChange(data, checked) {
      let chek = checked.checkedKeys.length;

      if (chek == 0) {
        this.isIndeterminate = false;
        this.checkAll = false;
      } else if (chek > 0 && this.OrganByCustomlenght != chek) {
        this.isIndeterminate = true;
        this.checkAll = false;
      } else {
        this.isIndeterminate = false;
        this.checkAll = true;
      }
    },
    //根据区域获取网点
    getAreaTreeByOrgandata() {
      ajax.get({
        url: this.$API.getAreaTreeByOrganId + this.orgid,
        success: (response) => {
          this.AreaTreeByOrgandata = response.data;
          this.AreaTreeByOrgandatalength = response.data.length;
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    // 切换网点
    selectaddOrganChange(value) {
    
      this.getGroupData()
      //this.getAreaTreeByOrgandata();
    },
    //添加区域点击区域
    dialogAreaTreeByOrganChange() {
      let areaIdList = [...this.areaIdList];
      let refAreaTreeByOrgandataTreeid =
        this.$refs.refAreaTreeByOrgandataTree.getCheckedKeys();
      areaIdList = [
        ...new Set([...areaIdList, ...refAreaTreeByOrgandataTreeid]),
      ];

      let refAreaTreeByOrgandataTreedata =
        this.$refs.refAreaTreeByOrgandataTree.getCheckedNodes();

      let areacheckdata = [...this.areacheckdata];
      areacheckdata = [...areacheckdata, ...refAreaTreeByOrgandataTreedata];

      areacheckdata = areacheckdata.reduce((acc, cur) => {
        if (acc.findIndex((data) => data.id == cur.id) === -1) {
          acc.push(cur);
        }
        return acc;
      }, []);

      this.areaIdList = [...areaIdList];
      this.areacheckdata = [...areacheckdata];
    },
    editAddreacheckdata(val) {
      this.$refs.refAreaTreeByOrgandataTree.setCheckedKeys(this.areaIdList);
      let index = this.areacheckdata.findIndex((data) => data.id == val);
      this.areacheckdata.splice(index, 1);
    },
    handleEditOrgan(data) {
      this.dialogEditOrganVisible = true;
      this.editorganuserid = data.id;
      ajax.get({
        url: this.$API.getUserOrgan + data.id,
        success: (response) => {
          this.UserBindOrgan = [];
          if (response.data.length > 0) {
            response.data.forEach((data) => {
              this.UserBindOrgan.push(data.id);
            });
          }
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    handleEditOrganchange(value, direction, movedKeys) {
      // console.log(value, direction, movedKeys)
      let self = this;
      //添加
      if (direction == "right") {
        axios
          .post(this.$API.userBindOrgan + this.editorganuserid, movedKeys)
          .then(function (res) {
            if (res.data.success) {
              self.$message({
                message: "网点添加成功",
                type: "success",
              });
            }
          });
      }
      //移除
      else {
        axios
          .post(this.$API.userUnBindOrgan + this.editorganuserid, movedKeys)
          .then(function (res) {
            if (res.data.success) {
              self.$message({
                message: "网点移除成功",
                type: "success",
              });
            }
          });
      }
    },
    handleAuditDisable() {
      this.dialogAuditVisible = true;
      this.getUserListAudit();
    },
   
  
    handleAuditVisible(row) {
      this.Audituser=row
      this.dialogAuditactiveUserVisible=true
    },
    handleAudit() {
      let self =this
      if(self.quartzGroupId !=null){
        this.$confirm("确定审核通过用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let attr = {};
          attr.state = 1;
          attr.id = self.Audituser.id;
          attr.customerId = self.$store.getters.customerId;
        
          ajax.post({
            url: this.$API.addUser,
            data: attr,
            success: (response) => {
              //console.log(response)
              if (response.success) {
                let list=[
                  {
                    quartzGroupId: self.quartzGroupId,
                    userId: self.Audituser.id,
                    layoutId: self.layoutsid
                  }
                ]
                 axios
                .post(this.$API.userBindOrgan + self.Audituser.id, [self.orgid])
                .then(function (res) {
                  return
                });
                axios
                .post(this.$API.bindUserQuartzGroupTarget, list)
                .then(function (res) {
                  if (res.data.success) {
                    self.getUserListAudit();
                    self.getUserListData();
                    self.dialogAuditactiveUserVisible=false
                    self.$message({
                      message: "审核成功",
                      type: "success",
                    });
                      }
                });
              
              } else {
                this.$message({
                  message: response.message,
                  type: "warning",
                });
              }
            },
            error: (res) => {
              //console.log(res)
              this.$message({
                message: res.message,
                type: "error",
              });
            },
          });
        })
        .catch(() => {});
      }
      else{
        this.$message({
          message: '用户分组不能为空,请分配用户分组',
          type: "warning",
        });
      }
      
    },
    getUserListAudit() {
      ajax.post({
        url: this.$API.getUserListAudit,
        success: (response) => {
          if (response.data.length > 0) {
            this.Auditdata = response.data;
          }
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    resetAudita(){
      this.Auditactive = 0;
      this.organIdList = [];
      this.organcheckdata = [];
      this.areaIdList = [];
      this.areacheckdata = [];
      this.AreaTreeByOrgandata = [];
      this.$refs.Organtree.setCheckedNodes([]);
      this.checkAll = false;
    },
    // 获取控制组的数据
    getGroupData() {
      ajax.get({
        url: this.$API.getGroupByOrganIdAndType + `${this.orgid}/1`,
        success: (response) => {
          const resp = response.data;
          this.quartzGroupId=null
          if (resp.length > 0) {
           this.QuartzGroup=resp
           
          } else {
            this.$message({
              message: '当前网点没有分组请先创建分组',
              type: "warning",
            });
            this.QuartzGroup=[]
          }
        },
      });
    },
    //
    selectquartzGroupChange(){
      let self = this;
      let params = new URLSearchParams(); 
      //type 1为分组 0为用户
      params.append("groupId", this.quartzGroupId);
      params.append("userId", '');
      axios
      .post(self.$API.getGroupLayoutsByUserIdAndGroupId, params)
      .then(function (res) {
        if (res.data.success) {
          if (res.data.data!='' && res.data.data.length > 0) {
              self.layoutsid =res.data.data[0].id
            }
            else{
              self.layoutsid =null
            }
        }
      });
    },
 
    
  },
  // 过滤器
  filters: {
    roleTypeFilter(type) {
      const roleObj = roleOptions.find((obj) => obj.type === type);
      return roleObj ? roleObj.name : null;
    },
    statusFilter(type) {
      const roleObj = statusOptions.find((obj) => obj.type === type);
      return roleObj ? roleObj.name : null;
    },
    WhtokWh(Wh) {
      if (Wh == null) {
        return "-";
      } else {
        return Wh / 1000;
      }
    },
    mintoH(min) {
      let stomin = min / 60;
      if (min < 60) {
        return min + "秒";
      } else {
        if (stomin < 60) {
          return (stomin % 60).toFixed(1) + "分钟";
        } else {
          return (
            Math.floor(stomin / 60) + "时" + (stomin % 60).toFixed(1) + "分钟"
          );
        }
      }
    },
    getorganName(id) {
      let organName = organOptions.find((obj) => obj.id === id);
      return organName ? organName.name : "--";
    },
  },
};
function twoTimeInterval(startTime, endTime) {
  // 开始时间
  // let d1 = startTime.replace(/\-/g, "/");
  let date1 = new Date(startTime);

  // 结束时间

  let date2 = new Date(endTime);

  // 时间相差秒数
  let dateDiff = date2.getTime() - date1.getTime();
  let minutes = Math.floor(dateDiff / (60 * 1000 * 60));
  return minutes;
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/styles/variables.styl';

.user-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 0.2rem;
  overflow: auto;
  background-color: $pageBg;

  .diolog-group-table {
    display: flex;

    .dialog-group-btn {
      // width: 1rem
      padding: 0.2rem;
      display: flex;
      flex-direction: column;
      box-sizing: border-box;

      .el-button {
        margin: 0.2rem 0 0;
      }
    }
  }

  .dialog-area-head {
    display: flex;
    justify-content: space-between;
  }
}

>>> {
  .el-table__body-wrapper {
    overflow-y: auto !important;
  }

  .el-table .el-checkbox__label {
    color: #fff;
  }
}

>>>.add-user-dia {
  .el-form .el-form-item:last-child {
    margin-bottom: 0;
  }

  .el-dialog__footer {
    padding: 0 0.3rem 0.3rem;
  }
}

.close-box {
  margin-top: 0.3rem;
  text-align: center;
}

>>>.group-dia {
  .el-table {
    height: 5rem;
  }
}

.manager-row {
  display: flex;
  height: 40px;
  align-items: center;
}

>>>.addusersteps .el-step__head.is-process {
  border-color: #67C23A;
}

>>>.addusersteps .el-step__title.is-process {
  color: #fff;
}

>>>.Organtree.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
  background: none !important;
  color: #fff !important;
}

>>>.checkall.el-checkbox {
  padding-left: 32px;
  margin-top: 15px;
}

>>>.checkall.el-checkbox .el-checkbox__label {
  font-size: 0.16rem;
  color: #fff;
}

>>>.shuttle-row .el-transfer-panel {
  background: none;
}

>>>.shuttle-row .el-transfer-panel__item.el-checkbox {
  color: #fff;
}

>>>.shuttle-row .el-transfer__button {
  display: block;
  margin: 0;
  width: 90px;
  margin-top: 10px;
}

.manager-row [class*=' el-icon-'] {
  color: #fff;
  font-size: 20px;
  margin-top: 4px;
  margin-left: 10px;
}
</style>
